package study.async.springboot.controller;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import study.eggs.result.Result;
import study.eggs.result.Results;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class _5_DeferredResultController {

    private static ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
            .setNameFormat("my-pool-thread-%d")
            .build();

    private static ExecutorService POOL = Executors.newFixedThreadPool(5, THREAD_FACTORY);

    @RequestMapping("/deferredResult")
    @ResponseBody
    public DeferredResult<Result> deferred() {
        log.info(">>>>>> i am controller");

        //step-1: 设置超时时间
        DeferredResult<Result> result = new DeferredResult<>(60 * 1000L);

        //step-2: 事件监听，采用委托机制
        result.onTimeout(() -> {
            log.info("超时");
            result.setResult(Results.fail());
        });
        result.onCompletion(() -> {
            log.info("调用完成");
        });

        //step-3: 执行任务
        POOL.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            //处理业务逻辑
            log.info(">>>>>> i am Business logic");
            //返回结果
            result.setResult(Results.ok());
        });

        return result;
    }
}
